package cn.edu.cqu.zhihucrawler2.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cn.edu.cqu.zhihucrawler2.R;
import cn.edu.cqu.zhihucrawler2.commen.CommenValue;
import cn.edu.cqu.zhihucrawler2.commen.LoadMoreListView;
import cn.edu.cqu.zhihucrawler2.domain.ZhihuAnswer;


/**
 * A placeholder fragment containing a simple view.
 */
public class AnswerFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, LoadMoreListView.OnLoadMore
{
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";
    private SearchTask mAuthTask = null;
    private LoadMoreListView listView_answer;
    private Spinner spinner;
    private SwipeRefreshLayout swip;
    private SimpleAdapter adapter;
    private int page = 0;
    private View mProgressView, mContentView;
    private List<Map<String, Object>> answersList = new LinkedList<>();
    private LinkedList<Map.Entry<String, String>> inputAnswerURL = CommenValue.answerURL1;

    public AnswerFragment()
    {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static AnswerFragment newInstance(int sectionNumber)
    {
        AnswerFragment fragment = new AnswerFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        View rootView= inflater.inflate(R.layout.fragment_answers, container, false);
        mProgressView = rootView.findViewById(R.id.show_progress);
        mContentView = rootView.findViewById(R.id.show_content);
        initView(rootView);
        initData(page++);
        return rootView;
    }

    private void initData(int pageNo)
    {
        LinkedList<Map.Entry<String, String>> topicURL = inputAnswerURL;
        mAuthTask = new SearchTask(getContext(),topicURL.get(pageNo));
        mAuthTask.execute();
    }

    private void initView(View rootView)
    {
        //主体展示
        setListView(rootView);
        setSpinner(rootView);
    }

    private void setListView(View rootView)
    {
        listView_answer = (LoadMoreListView) rootView.findViewById(R.id.listView_answer);
        listView_answer.setLoadMoreListen(this);
        swip = (SwipeRefreshLayout) rootView.findViewById(R.id.swip_index);
        swip.setOnRefreshListener(this);
        swip.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        adapter = new SimpleAdapter(getContext(),answersList,R.layout.answer_layout,
                new String[]{"title","content","likeCount","topic"},
                new int[]{R.id.textView_title,R.id.textView_content,R.id.textView_likeCount,R.id.textView_topic});
        listView_answer.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
            {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                Uri content_url = Uri.parse(answersList.get(i).get("url").toString());
                intent.setData(content_url);
                startActivity(intent);
            }
        });
        listView_answer.setAdapter(adapter);
    }

    private void setSpinner(final View rootView)
    {
        spinner = (Spinner) rootView.findViewById(R.id.spinner);
        spinner.setSelection(0,false);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
            {

                switch (i)
                {
                    case 1:
                        inputAnswerURL = CommenValue.answerURL2;
                        break;
                    case 2:
                        inputAnswerURL = CommenValue.answerURL3;
                        break;
                    case 3:
                        inputAnswerURL = CommenValue.answerURL4;
                        break;
                    case 4:
                        inputAnswerURL = CommenValue.answerURL5;
                        break;
                    case 5:
                        inputAnswerURL = CommenValue.answerURL6;
                        break;
                    case 6:
                        inputAnswerURL = CommenValue.answerURL7;
                        break;
                    default:
                    case 0:
                        inputAnswerURL = CommenValue.answerURL1;
                        break;
                }
                listView_answer.onLoading();
                answersList.clear();
                adapter.notifyDataSetChanged();
                page = 0;//重置页数
                initData(page++);
//                Set<Map.Entry<String, String>> entrySet = inputAnswerURL.entrySet();
//                for (Map.Entry<String, String> stringStringEntry : entrySet)
//                {
//                    mAuthTask = new SearchTask(getContext(), stringStringEntry);
//                    mAuthTask.execute();
//                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView)
            {

            }
        });
    }

    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mContentView.setVisibility(show ? View.GONE : View.VISIBLE);
            mContentView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mContentView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mContentView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void onRefresh()
    {
        if(getUserVisibleHint())
            Toast.makeText(getActivity(), "开始刷新", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(swip.isShown()){
                    swip.setRefreshing(false);
                }
                if(getUserVisibleHint())
                    Toast.makeText(getActivity(), "刷新完成", Toast.LENGTH_SHORT).show();
            }
        }, 3000);
    }

    @Override
    public void loadMore()
    {
        if(page >= inputAnswerURL.size())
        {
            if(getUserVisibleHint())
            {
                Toast.makeText(getActivity(), "已经是最后一页了", Toast.LENGTH_SHORT).show();
                listView_answer.onLoadComplete();
            }
            return;
        }
        else
        {
            initData(page);
            page++;
        }
    }

    private class SearchTask extends AsyncTask<Void, Void, Boolean>
    {
        Context context;
        Map.Entry<String,String>  topicURL;

        public SearchTask(Context context,Map.Entry<String,String> topicURL)
        {
//            showProgress(true);
            this.context = context;
            this.topicURL = topicURL;
        }

        @Override
        protected Boolean doInBackground(Void... voids)
        {
            Connection conn= Jsoup.connect("https://www.zhihu.com/topic/" + topicURL.getValue()+ "/hot");
            Document doc;
            try
            {
                doc = conn.get();
                Elements answerList = doc.select("div[class=ContentItem AnswerItem]");
                for (Element element : answerList)
                {
                    Map<String, Object> map = new HashMap<>();
                    //作者 标题
                    JsonParser parser = new JsonParser();
                    JsonObject data = parser.parse(element.attr("data-zop")).getAsJsonObject();
                    String authorName = data.get("authorName").getAsString();
                    String title = data.get("title").getAsString();
                    map.put("title", title);
                    //简略内容
                    Elements spanContent = element.select("span[class=RichText CopyrightRichText-richText]");
                    String minContent = spanContent.text();
                    map.put("content", authorName+":"+minContent);
                    //赞数
                    Elements likeCountButton = element.select("button[class=Button VoteButton VoteButton--up]");
                    String likeCount = likeCountButton.text();
                    map.put("likeCount", likeCount+"点赞");
                    //回答URL
                    String url = element.getElementsByAttributeValue("itemprop", "url").get(2).attr("content");
                    map.put("url", url);
                    map.put("topic",topicURL.getKey());
                    answersList.add(map);
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            if (success) {
                listView_answer.onLoadComplete();
                adapter.notifyDataSetChanged();
                if(getUserVisibleHint())
                    Toast.makeText(getActivity(), "加载完成", Toast.LENGTH_SHORT).show();
            } else {
                if(getUserVisibleHint())
                    Toast.makeText(getActivity(),"连接服务器出错",Toast.LENGTH_SHORT).show();
            }
//            showProgress(false);
            mAuthTask = null;
        }

        @Override
        protected void onCancelled() {
//            showProgress(false);
            mAuthTask = null;
        }
    }
}